from django.http.response import JsonResponse
from django.shortcuts import redirect, render
from django.views.generic import View, CreateView
from django.urls import reverse_lazy, reverse
# Create your views here.
from dadmin.views import HasLoginRequired
from order.models import DmallCart
from order.forms import DmallCartForm
from DjangoMall.views import BaseGoodsView

 
class DmallCartCreateView(HasLoginRequired, BaseGoodsView, CreateView):
    model = DmallCart
    template_name = "order/add_cart.html"
    fields = ('goods','sku','num')
    # form_class = DmallCartForm

    # def form_valid(self, form):
    #     form.instance.owner = self.request.user
    #     return super().form_valid(form)
    
    # def get_success_url(self) -> str:
    #     return reverse('goods:goods-detail', kwargs={'pk': self.get_form().instance.goods.id})

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        # 为前端购物车构造数据格式 data = [{},{}]
        fields = []
        for data in queryset:
            good_dict = dict()
            good_dict['nums'] = data.num
            good_dict['shop_price'] = '%.2f' % (data.goods.shop_price)
            good_dict['title'] = data.goods.title
            good_dict['image'] = '<figure class="image is-64x64"><img  src="/media/{}"></figure>'.format(data.goods.image)
            good_dict['goods_money'] = '%.2f' % (good_dict['nums'] * data.goods.shop_price)

            good_dict['input_num'] = '''
                <input class="input has-text-centered" type="number" onkeydown="return false;" min=1 value="{}" max="{}">
            '''.format(data.num, data.goods.goods_stock)
            # .format(num=data.num, max=data.goods.goods_stock)
            fields.append(good_dict)

        import json
        datas = json.dumps(fields, ensure_ascii=False)
        context = {}
        context['carts_json'] = datas
        if self.request.user.is_authenticated:
            context['cart_num'] = DmallCart.get_cart_num(self.request.user)
            context['carts'] = DmallCart.get_cart_owner(self.request.user)
            context['sum_money'], context['goods_num']  = DmallCart.get_cart_sum_money(self.request.user)
        return render(request, 'order/add_cart.html', context)




    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            new_cart = form.save(commit=False)
            new_cart.owner = self.request.user
            cart = DmallCart.objects.filter(goods=new_cart.goods, owner=new_cart.owner).last()
            if cart:
                a = DmallCart.objects.get(id=cart.id)
                a.num = new_cart.num + cart.num
                a.save()
                return JsonResponse({'code': 2001 , 'goods': cart.goods.id,  'message': '添加到购物车成功'})
            elif cart == None:
                new_cart.save()
                return JsonResponse({'code': 2001 , 'goods': new_cart.goods.id, 'message': '已成功添加到购物车'})
        # return render(request, "order/add_cart.html", {'form': form})
        
        return JsonResponse({'ceshi':'sada'})